<?php

/**
 * This is the model class for table "news_category".
 *
 * The followings are the available columns in table 'news_category':
 * @property string $id
 * @property string $url_key
 * @property string $name
 * @property integer $index
 * @property string $parent_id
 *
 * The followings are the available model relations:
 * @property Article[] $articles
 * @property NewsCategory $parent
 * @property NewsCategory[] $newsCategories
 */
class NewsCategory extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return NewsCategory the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	function behaviors()
	{
		return array(
			'movable'=>array(
				'class'=>'ext.common.behaviors.MovableActiveRecordBehavior',
			'groupDetect'=>array('parent_id'),
		),
		);
	}

	function defaultScope()
	{
		return array(
			'order'=>'`parent_id`, `index`',
		);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'news_category';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('url_key, name', 'required'),
			array('index', 'numerical', 'integerOnly'=>true),
			array('url_key, name', 'length', 'max'=>255),
			array('parent_id', 'length', 'max'=>11),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, url_key, name, index, parent_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'articles' => array(self::HAS_MANY, 'Article', 'cat_id'),
			'parent' => array(self::BELONGS_TO, 'NewsCategory', 'parent_id'),
			'newsCategories' => array(self::HAS_MANY, 'NewsCategory', 'parent_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'url_key' => 'Url Key',
			'name' => 'Name',
			'index' => 'Index',
			'parent_id' => 'Parent',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('url_key',$this->url_key,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('index',$this->index);
		$criteria->compare('parent_id',$this->parent_id,true);

		$criteria->addCondition('parent_id is null');

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

		public function  getParents()
	{
		if (!isset($this->_parents)) {
			$path = array();
			if (!is_null($this->parent_id)) {
				$path = $this->parent->getParents();
				$path[] = $this->parent;
			}

			array_reverse($path);
			$this->_parents = $path;
		}
		return $this->_parents;
	}

	public function getUrlPath()
	{
		if (!isset($this->_url_path)) {
			$urls = array();
			foreach ($this->parents as $p) $urls[] = $p->url_key;
			$this->_url_path = $urls;
		}
		return $this->_url_path;
	}

	function getRecommendedParents()
	{
		$allEntries = $this->findAll();

		if ($this->isNewRecord) return $allEntries;

		$ids = array($this->id);
		$finish = false;
		while (!$finish) {
			$finish = true;
			foreach ($allEntries as $i=>$e) {
				if (in_array($e->id, $ids)) {
					unset($allEntries[$i]);
					$finish = false;
					continue;
				}
				if (in_array($e->parent_id, $ids)) {
					$ids[] = $e->id;
					unset($allEntries[$i]);
					$finish = false;
				}
			}
		}
		return $allEntries;
	}

	function getChildren($count = 1000)
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $criteria=new CDbCriteria;
        if (empty($this->id)) $criteria->addCondition('parent_id IS NULL');
        else $criteria->compare('parent_id',$this->id);
        $criteria->order = '`index`';
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'pagination'    =>    array(
                'pageSize'    =>        $count,
            ),
        ));
    }
}